<!--
 * @Author: 李小晴 2689279066@qq.com
 * @Date: 2023-02-23 17:00:03
 * @LastEditors: 李小晴 2689279066@qq.com
 * @LastEditTime: 2023-06-21 09:59:39
 * @FilePath: \zhmc_pc\sys\src\views\SmartPasture\Logistics\Clean\Index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElMessageBox } from 'element-plus'
import { Dialog } from '@/components/Dialog'
import Edit from './components/Edit.vue'
import See from './components/See.vue'
import { unref } from 'vue'
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const userInfo: any = wsCache.get('userInfo')
// import { zcPastureListApi } from '@/api/sp/pasture'
// import { ucDeptListApi } from '@/api/uc/dept'
// import { adminFaUserListApi } from '@/api/fa/user'
import { Table } from '@/components/Table'

import { zcParkListApi, zcParkAddAdminApi, zcParkEditApi, zcParkDelApi } from '@/api/sp/park'

import { useTable } from '@/hooks/web/useTableTest'
import { ref, reactive } from 'vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useIcon } from '@/hooks/web/useIcon'

const saveLoading = ref(false) //保存中的状态
const iconEdit = useIcon({ icon: 'ep:edit' })
const iconSee = useIcon({ icon: 'ep:view' })
const iconDel = useIcon({ icon: 'ep:delete' })

const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: zcParkListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList, setSearchParams } = methods

getList()

const { t } = useI18n()
const crudSchemas = reactive<CrudSchema[]>([
  // {
  //   field: 'id',
  //   label: '主键',
  //   fixed: 'left',
  //   width: 60,
  //   table: {
  //     show: true
  //   },
  //   form: {
  //     show: false
  //   },
  //   detail: {
  //     show: false
  //   }
  // },
  {
    field: 'name',
    label: '园区名称',
    search: {
      show: false
    },
    form: {
      show: true
    }
  },
  {
    field: 'code',
    label: '编号',
    search: {
      show: false
    },
    form: {
      show: false
    }
  },
  {
    field: 'note',
    label: '备注',
    form: {
      show: true,
      component: 'Input',
      colProps: {
        span: 10
      }
    }
  },
  {
    field: 'create_user_name',
    label: '创建人',
    search: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'create_time',
    label: '创建时间',
    width: 170,
    form: {
      show: false
    },
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  {
    field: 'action',
    width: 150,
    fixed: 'right',
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const actionType = ref('')

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      console.log(tableObject.currentRow, 'ableObject.currentRow')
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {
        // is_stop: '0'
      }
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'file':
      ElMessageBox.confirm(`归档后不可以修改删除，是否归档？`, '归档', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 归档
          file()
          // deleteApi(data.knowledge_class_id)
        })
        .catch(() => {
          console.log('这里是取消归档')
        })
      break
    case 'del':
      ElMessageBox.confirm(`删除该园区？`, '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 归档
          del(row.id)
        })
        .catch(() => {
          console.log('取消删除该园区')
        })
      break
    default:
      console.log('未知类型')
  }
}
const del = async (val) => {
  saveLoading.value = true
  console.log('删除', 'bbb')
  let res = await zcParkDelApi({ id: val })
    .catch(() => {})
    .finally(() => {
      saveLoading.value = false
    })
  if (res) {
    getList()
  }
}
const file = () => {
  console.log('归档', 'aaa')
}
const editRef = ref<ComponentRef<typeof Edit>>()
const save = async () => {
  sessionStorage.removeItem('org_id')
  const edit = unref(editRef)
  switch (actionType.value) {
    case 'add':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          const data = (await edit?.getFormData()) as any
          console.log(data, 'data')
          data.type = '1'
          saveLoading.value = true
          // const data = (await edit?.getFormData()) as any
          console.log(data, 'data')
          const props = {
            my_org_id: userInfo.default_org_id,
            my_dept_id: userInfo.default_dept_id,
            name: data.name,
            note: data.note
          }
          let res = await zcParkAddAdminApi(props)
            .catch(() => {})
            .finally(() => {
              saveLoading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    case 'edit':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          saveLoading.value = true
          const data = (await edit?.getFormData()) as any
          console.log('data', data)
          const props = {
            id: data.id,
            admin_org_id: data.admin_org_id,
            admin_dept_id: data.admin_dept_id,
            admin_user_id: data.admin_user_id,
            name: data.name,
            note: data.note,
            is_del: '0'
          }
          let res = await zcParkEditApi(props)
            .catch(() => {})
            .finally(() => {
              saveLoading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    default:
      console.log('未知类型')
  }
}
const close = async () => {
  dialogVisible.value = false
  // sessionStorage.removeItem('org_id')
}
// const delData = async () => {
//   const { getSelections } = methods
//   const selections = await getSelections()
//   const ids = selections.map((v) => v.goods_id)
//   delLoading.value = true
//   ElMessageBox.confirm(t('common.delMessage'), t('common.delWarning'), {
//     confirmButtonText: t('common.delOk'),
//     cancelButtonText: t('common.delCancel'),
//     type: 'warning'
//   })
//     .then(async () => {
//       let res = await adminCsGoodsBatchDelApi({ ids: ids.join(',') })
//         .catch(() => {})
//         .finally(() => {
//           delLoading.value = false
//         })
//       if (res) {
//         getList()
//       }
//     })
//     .catch(() => {})
// }
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">新增</ElButton>
      <!-- <ElButton type="danger" @click="delData()">批量删除</ElButton> -->
    </div>
    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      :selection="false"
      @register="register"
    >
      <template #action="{ row }">
        <ElButton circle :icon="iconSee" @click="action('see', row)" title="查看" />
        <ElButton circle :icon="iconEdit" @click="action('edit', row)" title="编辑" />
        <ElButton circle :icon="iconDel" @click="action('del', row)" title="删除" />
      </template>
    </Table>
  </ContentWrap>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Edit
      v-if="actionType == 'edit' || actionType == 'add'"
      ref="editRef"
      :form-schema="allSchemas.formSchema"
      :current-row="tableObject.currentRow"
    />
    <See
      v-if="actionType == 'see'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />
    <template #footer>
      <ElButton
        v-if="actionType == 'add' || actionType == 'edit'"
        type="primary"
        :loading="saveLoading"
        @click="save()"
      >
        保存
      </ElButton>
      <ElButton @click="close()">关闭</ElButton>
    </template>
  </Dialog>
</template>
